<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :forceRender="true"
    v-bind:prefixNo="prefixNo"
    switchHelp
    switchFullscreen
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    :id="prefixNo"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleCXTJOk">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
            <a-row class="form-row" :gutter="24">
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('reportQuery.number')" data-step="2" :data-title="$t('setailManagement.documentNo')"
                  :data-intro="$t('popup.theDocumentOpened')">
                  <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="[ 'rebateCode' ]" :readOnly="true"/>
                </a-form-item>
              </a-col>
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.rebateName')" data-step="2" :data-title="$t('otherJS.rebateName')"
                  :data-intro="$t('otherJS.rebateName')">
                  <a-input :placeholder="$t('otherJS.pleaseEnterRebateName')" v-decorator="[ 'rebateName' ]" />
                </a-form-item>
              </a-col>
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.rebateMethod')" data-step="0" :data-title="$t('otherJS.rebateMethod')"
                             :data-intro="$t('otherJS.rebateMethod')">
                  <a-select :placeholder="$t('otherJS.selectRebateMethod')"  v-decorator="[ 'rebateMode', validatorRules.rebateMode ]" 
                            :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                    <a-select-option value="0">{{$t('otherJS.purchaseQuantityByCommodity')}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.calculationMethod')" data-step="0" :data-title="$t('otherJS.calculationMethod')"
                             :data-intro="$t('otherJS.calculationMethod')">
                  <a-select :placeholder="$t('otherJS.selectCalculationMethod')"  v-decorator="[ 'countMode', validatorRules.countMode ]"
                            :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                    <a-select-option value="0">{{$t('otherJS.rebateByCommodityAmountProportion')}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
                  <j-date v-decorator="['tabulationTime', validatorRules.tabulationTime]" :show-time="true"/>
                </a-form-item>
              </a-col>

              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :label="$t('otherJS.rebateDate')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-range-picker
                      style="width:100%"
                      v-decorator="[ 'createTimeRange', validatorRules.createTimeRange ]"
                      format="YYYY-MM-DD"
                      :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                      :placeholder="[$t('setailManagement.startTime'),$t('setailManagement.endTime')]"
                      @change="onDateCXTJChange"
                      @ok="onDateOk"
                    />
                </a-form-item>
              </a-col>
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.supplier')">
                  <a-select :placeholder="$t('manuManagement.selectSupplier')" 
                  v-decorator="[ 'supplierId', validatorRules.supplierName ]"  
                  allowClear
                  :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                    <div slot="dropdownRender" slot-scope="menu">
                      <v-nodes :vnodes="menu" />
                      <a-divider style="margin: 4px 0;" />
                      <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                           @mousedown="e => e.preventDefault()" @click="addSupplier"><a-icon type="plus" /> {{$t('popup.newSupplier')}}</div>
                    </div>
                    <a-select-option v-for="(item,index) in supList" :key="index" :value="item.id">
                      {{ item.supplier }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row class="form-row" :gutter="24">
                  <a-col :lg="24" :md="24" :sm="24">
                    <a-form-item :labelCol="labelCol" :wrapperCol="{xs: { span: 24 },sm: { span: 24 }}" label="">
                      <a-textarea :rows="1" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="[ 'remark' ]" style="margin-top:8px;"/>
                    </a-form-item>
                  </a-col>
                </a-row>
                <j-editable-table id="billModal"
                              :ref="refKeys[0]"
                              :loading="materialTable.loading"
                              :columns="materialTable.columns"
                              :dataSource="materialTable.dataSource"
                              :minWidth="minWidth"
                              :maxHeight="300"
                              :rowNumber="false"
                              :rowSelection="true"
                              :actionButton="true"
                              :dragSort="true"
                              @valueChange="onValueChange"
                              @added="onAdded"
                              @deleted="onDeleted">
            </j-editable-table>
        <!-- <a-tabs default-active-key="1">
          <a-tab-pane key="1" tab="返利设置" id="materialHeadModal" forceRender>
            <j-editable-table id="billModal"
                              :ref="refKeys[0]"
                              :loading="materialTable.loading"
                              :columns="materialTable.columns"
                              :dataSource="materialTable.dataSource"
                              :minWidth="minWidth"
                              :maxHeight="300"
                              :rowNumber="false"
                              :rowSelection="true"
                              :actionButton="true"
                              :dragSort="true"
                              @valueChange="onValueChange"
                              @added="onAdded"
                              @deleted="onDeleted">
            </j-editable-table>
          </a-tab-pane>
          <a-tab-pane key="2" tab="适用商品" id="materialHeadModal" forceRender>
            <j-editable-table id="billModal"
                              :ref="refKeys[0]"
                              :loading="rebateMaterialTable.loading"
                              :columns="rebateMaterialTable.columns"
                              :dataSource="rebateMaterialTable.dataSource"
                              :minWidth="minWidth"
                              :maxHeight="300"
                              :rowNumber="false"
                              :rowSelection="true"
                              :actionButton="true"
                              :dragSort="true"
                              @valueChange="onValueChange"
                              @added="onAdded"
                              @deleted="onDeleted">
            </j-editable-table>
          </a-tab-pane>
        </a-tabs> -->
      </a-form>
    </a-spin>
    <many-account-modal ref="manyAccountModalForm" @ok="manyAccountModalFormOk"></many-account-modal>
    <customer-modal ref="customerModalForm" @ok="customerModalFormOk"></customer-modal>
    <!-- <history-bill-list ref="historyBillListModalForm"></history-bill-list> -->
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import moment from 'moment';
  import { getAction } from '@/api/manage'
  import ManyAccountModal from '../dialog/ManyAccountModal'
  import CustomerModal from '../../system/modules/CustomerModal'
  import HistoryBillList from '../dialog/HistoryBillList'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { BillModalMixin } from '../mixins/BillModalMixin'
  import { getMpListShort,handleIntroJs } from "@/utils/util"
  import { BillListMixin } from '../mixins/BillListMixin'
  import JSelectMultiple from '@/components/jeecg/JSelectMultiple'
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  import Vue from 'vue'
  export default {
    name: "RebateModal",
    mixins: [JEditableTableMixin, BillModalMixin, BillListMixin],
    components: {
      ManyAccountModal,
      CustomerModal,
      HistoryBillList,
      JUpload,
      JDate,
      JSelectMultiple,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    provide(){
      return {
        getConfig: ()=>{
          return {organId : this.form.getFieldValue('supplierId')}
        }
      }
    },
    data () {
      return {
        title:this.$t('setailManagement.operation'),
        width: '1600px',
        queryParam: {
          holdSupplier: 1,
          holdDepot: 1,
        },
        UserHandler: [],
        moreStatus: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        priceVisible: false,
        visible: false,
        operTimeStr: '',
        prefixNo: 'FLHD',
        // fileList:[],
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        refKeys: ['materialDataTable'],
        activeKey: 'materialDataTable',
        materialTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: this.$t('otherJS.goodsId'), key: 'materialId', width: '7%', type: FormTypes.hidden },
            { title: this.$t('reportQuery.barcode'), key: 'barCode', width: '8%', type: FormTypes.popupJsh, kind: 'material', multi: true,
              // validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: this.$t('reportQuery.name'), key: 'name', width: '16%', type: FormTypes.normal },
            { title: this.$t('reportQuery.category'), key: 'categoryName', width: '6%', type: FormTypes.input,readonly:true  },
            { title: this.$t('otherJS.lowerLimit'), key: 'min', width: '7%', type: FormTypes.input},
            { title: this.$t('otherJS.upperLimit'), key: 'max', width: '7%', type: FormTypes.input},
            { title: this.$t('otherJS.profitRatio'), key: 'proportion', width: '7%', type: FormTypes.input},
            { title: this.$t('financialManagement.remarks'), key: 'remark', width: '7%', type: FormTypes.input},
          ]
        },
        rebateMaterialTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: this.$t('otherJS.goodsId'), key: 'materialId', width: '7%', type: FormTypes.hidden },
            { title: this.$t('reportQuery.barcode'), key: 'barCode', width: '8%', type: FormTypes.popupJsh, kind: 'material', multi: true,
              // validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: this.$t('reportQuery.name'), key: 'name', width: '6%', type: FormTypes.normal },
          ]
        },
        accountIdList: [],
        confirmLoading: false,
        validatorRules:{
          createTimeRange:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectDate')+'!' }
            ]
          },
          rebateName:{
            rules: [
              { required: true, message: this.$t('otherJS.pleaseEnterRebateName')+'!' }
            ]
          },
          tabulationTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseEnterDocumentDate')+'!' }
            ]
          },
          rebateMode:{
            rules: [
              { required: true, message: this.$t('otherJS.pleaseSelectRebateMethod')+'!' }
            ]
          },
          countMode:{
            rules: [
              { required: true, message: this.$t('otherJS.pleaseSelectCalculationMethod')+'!' }
            ]
          }
        },
        url: {
          add: '/rebate/add',
          edit: '/rebate/update',
          detailList: '/rebate/getDetailList'
        }
      }
    },
    created () {
    },
    methods: {
      moment,
      // priceList(item) {
      //   item.forEach((item1,index) => {
      //     item1.min = this.materialTable.dataSource[index].min
      //     item1.max = this.materialTable.dataSource[index].max
      //     item1.proportion = this.materialTable.dataSource[index].proportion
      //     item1.remark = this.materialTable.dataSource[index].remark
      //     item1.remark = this.materialTable.dataSource[index].remark
      //     item1.materialId = this.materialTable.dataSource[index].id
      //   })
      //   this.materialTable.dataSource = item
      // },
      visibleType(type){
        this.priceVisible = type
      },
      // 获取经手人
      getHandler() {
        let param = {
          'currentPage': '1',
          'pageSize': '10'
        }
        getAction("/person/list", param).then(res=>{
          if(res.code == '200') {
            this.UserHandler = res.data.rows
          }
        })
      },
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        this.getHandler()
        this.billStatus = '0'
        this.changeColumnHide()
        if (this.action === 'add') {
          this.addInit(this.prefixNo)
          this.personList.value = ''
          // this.fileList = []
          this.$nextTick(() => {
            handleIntroJs(this.prefixNo, 1)
          })
        } else {
          // this.model.name = this.model.materialName
          if(this.model.accountId == null) {
            this.model.accountId = 0
            this.manyAccountBtnStatus = true
            this.accountIdList = this.model.accountIdList
            this.accountMoneyList = this.model.accountMoneyList
          } else {
            this.manyAccountBtnStatus = false
          }
          this.personList.value = this.model.salesMan
          // 
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'remark', 'supplierName', 'createTimeRange', 'tabulationTime', 'countMode','supplierId', 'rebateMode', 'rebateName', 'rebateCode'))
            this.form.setFieldsValue({'createTimeRange': [moment(this.model.startTimeStr ),moment(this.model.endTimeStr) ] })
          });
          // 加载子表数据
          let params = {
            headerId: this.model.id,
            mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData1(url, params, this.materialTable);
        }
        //复制新增单据-初始化单号和日期
        if(this.action === 'copyAdd') {
          this.model.id = ''
          this.model.tenantId = ''
          this.copyAddInit(this.prefixNo)
        }
        this.initSupplier()
        this.initCustomer()
        this.initSalesman()
        this.initAccount()
      },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        let totalPrice = 0
        let billMain = Object.assign(this.model, allValues.formValue)
        let detailArr = allValues.tablesValue[0].values
        billMain.type = '其它'
        billMain.subType = '销售订单'
        billMain.defaultNumber = billMain.rebateCode
        for(let item of detailArr){
          item.depotId = '' //订单不需要仓库
          totalPrice += item.allPrice-0
        }
        billMain.totalPrice = totalPrice
        if(billMain.accountId === 0) {
          billMain.accountId = ''
        }
        if (!this.accountIdList) {
          billMain.accountIdList = ""
          billMain.accountMoneyList = ""
        } else {
          billMain.accountIdList = this.accountIdList.length>0 ? JSON.stringify(this.accountIdList) : ""
          billMain.accountMoneyList = this.accountMoneyList.length>0 ? JSON.stringify(this.accountMoneyList) : ""
        }
        // if(this.fileList && this.fileList.length > 0) {
        //   billMain.fileName = this.fileList
        // } else {
        //   billMain.fileName = ''
        // }
        if(this.model.id){
          billMain.id = this.model.id
        }
        billMain.salesMan = this.personList.value
        billMain.status = this.billStatus
        // let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        return {
          info: JSON.stringify(billMain),
          // attachment: fileList,
          rows: JSON.stringify(detailArr),
        }
      },
      handleHistoryBillList() {
        let holdSupplier = this.form.getFieldValue('holdSupplier')
        this.$refs.historyBillListModalForm.show(this.$t('manuManagement.other'),this.$t('manuManagement.salesOrder'),this.$t('manuManagement.customer'), holdSupplier);
        this.$refs.historyBillListModalForm.disableSubmit = false;
      },
    }
  }
</script>
<style scoped>

</style>